package de.pa2.proxy;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

import org.apache.http.Header;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpRequestHandler;
import org.slf4j.Logger;

public class DeadEndHttpRequestHandler implements HttpRequestHandler {
	private static final String EMPTY_IMAGE = "blank.gif";
	private static final String EMPTY_AD = "ad.js";

	private String baseUrl = "http://anti.proxy/";
	private static final Logger LOG = org.slf4j.LoggerFactory
			.getLogger(DeadEndHttpRequestHandler.class);

	public void handle(HttpRequest httprequest, HttpResponse response,
			HttpContext httpcontext) throws HttpException, IOException {
		String targetUrl = baseUrl + EMPTY_IMAGE;
		String requestedUrlString = httprequest.getRequestLine().getUri();
		Header refererHeader = httprequest.getFirstHeader("Referer");
		String referer = null;
		if (refererHeader != null) {
			referer = refererHeader.getValue();
		}
		try {
			URI requestedUrl = new URI(httprequest.getRequestLine().getUri());
			String path = requestedUrl.getPath();
			if ("ad.doubleclick.net".equals(requestedUrl.getHost())) {
				targetUrl = baseUrl + EMPTY_AD;
			} else if ("connect.facebook.net".equals(requestedUrl.getHost())) {
				targetUrl = baseUrl + "facebook_connect.js";
			} else if ("fips.uimserv.net".equals(requestedUrl.getHost())) {
				targetUrl = baseUrl + "empty.js";
			} else if ("www.facebook.com".equals(requestedUrl.getHost())) {
				if (path.startsWith("/plugins/like.php")) {
					targetUrl = baseUrl + "facebook_like.html";
				}
			}

		} catch (URISyntaxException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (LOG.isInfoEnabled()) {
			LOG.info("requested '" + requestedUrlString + "' (refered by '"
					+ referer + "') gets redirected to '" + targetUrl + "'");
		}
		response.setStatusCode(302);
		response.setHeader("Location", targetUrl);
	}
}
